package com.app.TCES.listener;

import java.util.HashMap;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


@WebListener
public class SessionListener implements HttpSessionListener {
	public static HashMap<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();

	private static int onlinePeople = 0;
	Logger log = LogManager.getLogger(SessionListener.class);
	
	@SuppressWarnings("unused")
	@Override
	public void sessionCreated(HttpSessionEvent httpSessionEvent) {
		//新的session
		HttpSession session = httpSessionEvent.getSession();

    	onlinePeople++;
		log.debug("当前人数："+onlinePeople);
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

		
		HttpSession session = httpSessionEvent.getSession();
		
		log.debug("delSession(session)");
		if(onlinePeople>0) {
    		onlinePeople--;
    	}
		delSession(session);
		
		log.debug("当前人数"+onlinePeople);
	}

	public static synchronized void delSession(HttpSession session) {

		if (session != null) {

			// 删除单一登录中记录的变量
			if (session.getAttribute("userName") != null) {
				
				SessionListener.sessionMap.remove(session.getAttribute("userName"));
				
			}
		}
	}
}
